package com.folioreader.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.folioreader.Config;
import com.folioreader.Constants;
import com.folioreader.FolioReader;
import com.folioreader.R;
import com.folioreader.model.DisplayUnit;
import com.folioreader.model.HighlightImpl;
import com.folioreader.model.locators.ReadLocator;
import com.folioreader.model.locators.SearchLocator;
import com.folioreader.ui.adapter.FolioPageFragmentAdapter;
import com.folioreader.ui.adapter.SearchAdapter;
import com.folioreader.ui.fragment.FolioPageFragment;
import com.folioreader.ui.fragment.MediaControllerFragment;
import com.folioreader.ui.view.DirectionalViewpager;
import com.folioreader.ui.view.FolioAppBarLayoutNew;
import com.folioreader.ui.view.MediaControllerCallback;
import com.folioreader.util.AppUtilNew;
import com.folioreader.util.FileUtil;
import com.folioreader.util.UiUtil;

import org.readium.r2.shared.Link;
import org.readium.r2.shared.Publication;
import org.readium.r2.streamer.parser.CbzParser;
import org.readium.r2.streamer.parser.EpubParser;
import org.readium.r2.streamer.parser.PubBox;
import org.readium.r2.streamer.server.Server;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class FolioActivityNew extends AppCompatActivity implements FolioActivityCallback, MediaControllerCallback,
        View.OnSystemUiVisibilityChangeListener {

    public static final int CONTENT_HIGHLIGHT = 77;
    public static final int SEARCH = 101;


    private String bookFileName = null;
    private DirectionalViewpager mFolioPageViewPage = null;
    private ActionBar actionBar = null;
    private FolioAppBarLayoutNew appBarLayoutNew = null;
    private Toolbar toolbar = null;
    private boolean distractionFreeMode = false;
    private Handler handler = null;

    private int currentChpterIndex = 0;
    private FolioPageFragmentAdapter folioPageFragmentAdapte = null;
    private ReadLocator entryReadLocator = null;
    private ReadLocator lastReadLocator = null;
    private Bundle outState = null;
    private Bundle saveInstanceState = null;

    private Server r2StreamerServer = null;
    private PubBox pubBox = null;
    private List<Link> spine = null;

    private String mBookId = null;
    private String mEpubFilePath = null;
    private EpubSourceType mEpubsourceType = null;
    private int mEpubRawId = 0;
    private MediaControllerFragment mediaControllerFragment = null;
    private Config.Direction direction = Config.Direction.VERTICAL;

    private int portNumber = Constants.DEFAULT_PORT_NUMBER;
    private Uri streamerUri = null;

    private Uri searchUri = null;
    private Bundle searchAdapterDataBundle = null;
    private CharSequence searchQuery = null;
    private SearchLocator searchLocator = null;

    private DisplayMetrics displayMetrics = null;
    private float density = 0f;
    private boolean topActivity = false;
    private int taskImportance = 0;


    public static final String INTENT_EPUB_SOURCE_PATH = "com.folioreader.epub_asset_path";
    public static final String INTENT_EPUB_SOURCE_TYPE = "epub_source_type";
    public static final String EXTRA_READ_LOCATOR = "com.folioreader.extra.READ_LOCATOR";
    public static final String BUNDLE_READ_LOCATOR_CONFIG_CHANGE = "BUNDLE_READ_LOCATOR_CONFIG_CHANGE";
    public static final String BUNDLE_DISTRACTION_FREE_MODE = "BUNDLE_DISTRACTION_FREE_MODE";
    public static final String EXTRA_SEARCH_ITEM = "EXTRA_SEARCH_ITEM";
    public static final String ACTION_SEARCH_CLEAR = "ACTION_SEARCH_CLEAR";
    public static final String HIGHLIGHT_ITEM = "highlight_item";

    private BroadcastReceiver closeBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null && action == FolioReader.ACTION_CLOSE_FOLIOREADER) {
                try {
                    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                    taskImportance = activityManager.getRunningAppProcesses().get(0).importance;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Intent closeIntent = new Intent(getApplicationContext(), FolioActivityNew.class);
            closeIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            closeIntent.setAction(FolioReader.ACTION_CLOSE_FOLIOREADER);
            startActivity(closeIntent);
        }
    };

    private int statusBarHeight;

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private BroadcastReceiver searchReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.isEmpty()) {
                return;
            }
            if (action == ACTION_SEARCH_CLEAR) {
                clearSearchLocator();
            }
        }
    };

    private FolioPageFragment currentFragment = getCurrentFragment();

    public FolioPageFragment getCurrentFragment() {
        if (folioPageFragmentAdapte != null && mFolioPageViewPage != null) {
            return (FolioPageFragment) folioPageFragmentAdapte.getItem(mFolioPageViewPage.getCurrentItem());
        } else {
            return null;
        }
    }

    public enum EpubSourceType {
        RAW,
        ASSETS,
        SD_CARD
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        String action = intent.getAction();
        if (action != null && action == FolioReader.ACTION_CLOSE_FOLIOREADER) {
            if (topActivity == false) {
                finish();
                boolean appInBackground = false;
                if (Build.VERSION.SDK_INT < 26) {
                    if (ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND == taskImportance)
                        appInBackground = true;
                } else {
                    if (ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED == taskImportance)
                        appInBackground = true;
                }
                if (appInBackground)
                    moveTaskToBack(true);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        topActivity = true;
        String action = getIntent().getAction();
        if (action != null && action == FolioReader.ACTION_CLOSE_FOLIOREADER) {
            // FolioActivity is topActivity, so need to broadcast ReadLocator.
            finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        topActivity = false;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //全屏显示
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

        handler = new Handler();
        statusBarHeight = getStatusBarHeight();

        Display display = getWindowManager().getDefaultDisplay();
        displayMetrics = getResources().getDisplayMetrics();
        display.getRealMetrics(displayMetrics);
        density = displayMetrics.density;
        LocalBroadcastManager.getInstance(this).registerReceiver(closeBroadcastReceiver,new  IntentFilter(FolioReader.ACTION_CLOSE_FOLIOREADER));

        setConfig(savedInstanceState);
        initDistractionFreeMode(savedInstanceState);

        setContentView(R.layout.folio_activity);
        this.saveInstanceState = savedInstanceState;

        if (savedInstanceState != null) {
            searchAdapterDataBundle = savedInstanceState.getBundle(SearchAdapter.DATA_BUNDLE);
            searchQuery = savedInstanceState.getCharSequence(SearchActivity.BUNDLE_SAVE_SEARCH_QUERY);
        }
        mBookId = getIntent().getStringExtra(FolioReader.EXTRA_BOOK_ID);
        mEpubsourceType = (EpubSourceType) getIntent().getExtras().getSerializable(INTENT_EPUB_SOURCE_TYPE);
        if (mEpubsourceType == FolioActivityNew.EpubSourceType.RAW) {
            mEpubRawId = getIntent().getExtras().getInt(FolioActivityNew.INTENT_EPUB_SOURCE_PATH);
        } else {
            mEpubFilePath = getIntent().getExtras().getString(FolioActivityNew.INTENT_EPUB_SOURCE_PATH);
        }
        initActionBar();
        initMediaController();
        if (ContextCompat.checkSelfPermission(FolioActivityNew.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,Constants.getWriteExternalStoragePerms(),Constants.WRITE_EXTERNAL_STORAGE_REQUEST);
        }else{
            setupBook();
        }

    }

    private void initActionBar() {
        appBarLayoutNew = findViewById(R.id.appBarLayout);
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        actionBar = getSupportActionBar();
        Config config = AppUtilNew.getSavedConfig(getApplicationContext());
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.ic_drawer);
        UiUtil.setColorIntToDrawable(config.getThemeColor(), drawable);
        toolbar.setNavigationIcon(drawable);
        if (config.isNightMode()) {
            setNightMode();
        } else {
            setDayMode();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int color;
            if (config.isNightMode()) {
                color = ContextCompat.getColor(this, R.color.black);
            } else {
                int[] attrs = new int[]{android.R.attr.navigationBarColor};
                TypedArray typedArray = getTheme().obtainStyledAttributes(attrs);
                color = typedArray.getColor(0, ContextCompat.getColor(this, R.color.white));

            }
            getWindow().setNavigationBarColor(color);
        }
        if (Build.VERSION.SDK_INT < 16) {
            appBarLayoutNew.setTopMargin(statusBarHeight);
        }
    }

    private void initMediaController() {
        mediaControllerFragment = MediaControllerFragment.getInstance(getSupportFragmentManager(), this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        Config config = AppUtilNew.getSavedConfig(getApplicationContext());
        UiUtil.setColorIntToDrawable(config.getThemeColor(), menu.findItem(R.id.itemSearch).getIcon());
        UiUtil.setColorIntToDrawable(config.getThemeColor(), menu.findItem(R.id.itemConfig).getIcon());
        UiUtil.setColorIntToDrawable(config.getThemeColor(), menu.findItem(R.id.itemTts).getIcon());

        if (!config.isShowTts())
            menu.findItem(R.id.itemTts).setVisible(false);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            startContentHighlightActivity();
            return true;
        } else if (itemId == R.id.itemSearch) {
            if (searchUri == null)
                return true;

            Intent intent = new Intent(this, SearchActivity.class);
            intent.putExtra(SearchActivity.BUNDLE_SPINE_SIZE, spine != null ? spine.size() : 0);
            intent.putExtra(SearchActivity.BUNDLE_SEARCH_URI, searchUri);
            intent.putExtra(SearchAdapter.DATA_BUNDLE, searchAdapterDataBundle);
            intent.putExtra(SearchActivity.BUNDLE_SAVE_SEARCH_QUERY, searchQuery);
            startActivityForResult(intent, SEARCH);

            return true;
        } else if (itemId == R.id.itemConfig) {
            showConfigBottomSheetDialogFragment();
            return true;
        } else if (itemId == R.id.itemTts) {
//            showMediaController();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void startContentHighlightActivity() {
        Intent intent = new Intent(this, ContentHighlightActivity.class);
        intent.putExtra(Constants.PUBLICATION, pubBox.getPublication());
        try {
            intent.putExtra(Constants.CHAPTER_SELECTED, spine.get(currentChpterIndex).getHref());
        } catch (Exception e) {
            e.printStackTrace();
            intent.putExtra(Constants.CHAPTER_SELECTED, "");
        }
        intent.putExtra(FolioReader.EXTRA_BOOK_ID, mBookId);
        intent.putExtra(Constants.BOOK_TITLE, bookFileName);

        startActivityForResult(intent, CONTENT_HIGHLIGHT);
        overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);

    }

    //显示底部的菜单
    public void showConfigBottomSheetDialogFragment() {
        Toast.makeText(this, "showConfigBottomSheetDialogFragment", Toast.LENGTH_SHORT).show();
    }

    /**
     * 打开书籍
     */
    private void setupBook() {
        try {
            initBook();
            onBookInitSuccess();
        } catch (Exception e) {
            onBookInitFailure();
        }
    }

    /**
     * 初始化书籍
     */
    private void initBook() {
        bookFileName = FileUtil.getEpubFilename(this, mEpubsourceType, mEpubFilePath, mEpubRawId);
        String path = FileUtil.saveEpubFileAndLoadLazyBook(this, mEpubsourceType, mEpubFilePath, mEpubRawId, bookFileName);

        Publication.EXTENSION extension;
        String extensionString = null;
        try {
            extensionString = FileUtil.getExtensionUppercase(path);
            extension = Publication.EXTENSION.valueOf(extensionString);

            if (extension == Publication.EXTENSION.EPUB) {
                EpubParser epubParser = new EpubParser();
                pubBox = epubParser.parse(path, "");
            } else if (extension == Publication.EXTENSION.CBZ) {
                CbzParser cbzParser = new CbzParser();
                pubBox = cbzParser.parse(path, "");
            } else {
                pubBox = null;
            }
            portNumber = getIntent().getIntExtra(FolioReader.EXTRA_PORT_NUMBER, Constants.DEFAULT_PORT_NUMBER);
            portNumber = AppUtilNew.getAvailablePortNumber(portNumber);

            r2StreamerServer = new Server(portNumber);
            r2StreamerServer.addEpub(pubBox.getPublication(), pubBox.getContainer(), "/" + bookFileName, null);
            r2StreamerServer.start();
            FolioReader.initRetrofit(getStreamerUrl());

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void onBookInitFailure() {

    }

    private void onBookInitSuccess() {
        Publication publication = pubBox.getPublication();
        spine = publication.getReadingOrder();
        setTitle(publication.getMetadata().getTitle());
        if (mBookId == null) {
            if (!publication.getMetadata().identifier.isEmpty()) {
                mBookId = publication.getMetadata().identifier;
            } else {
                if (!publication.getMetadata().getTitle().isEmpty()) {
                    mBookId = publication.getMetadata().getTitle().hashCode() + "";
                } else {
                    mBookId = bookFileName.hashCode() + "";
                }
            }
        }
        for (Link link : publication.getLinks()) {
            if (link.getRel().contains("search")) {
                searchUri = Uri.parse("http://" + link.getHref());
                break;
            }
        }
        if (searchUri == null) {
            searchUri = Uri.parse(getStreamerUrl() + "search");
        }
        configFolio();
    }

    private void initDistractionFreeMode(Bundle savedInstanceState) {
        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(this);
        hideSystemUI();
        showSystemUI();
        distractionFreeMode = savedInstanceState != null && savedInstanceState.getBoolean(BUNDLE_DISTRACTION_FREE_MODE);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if (distractionFreeMode) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    hideSystemUI();
                }
            });
        }
    }

    @Override
    public void onSystemUiVisibilityChange(int visibility) {
        distractionFreeMode = visibility != View.SYSTEM_UI_FLAG_VISIBLE;
        if (actionBar != null) {
            if (distractionFreeMode) {
                actionBar.hide();
            } else {
                actionBar.show();
            }
        }
    }

    @Override
    public int getCurrentChapterIndex() {
        return currentChpterIndex;
    }

    @Override
    public ReadLocator getEntryReadLocator() {
        if (entryReadLocator != null) {
            ReadLocator tempReadLocator = entryReadLocator;
            entryReadLocator = null;
            return tempReadLocator;
        }
        return null;
    }

    @Override
    public boolean goToChapter(String href) {
        for (Link link : spine) {
            if (href.contains(link.getHref())) {
                currentChpterIndex = spine.indexOf(link);
                mFolioPageViewPage.setCurrentItem(currentChpterIndex);
                FolioPageFragment folioPageFragment = currentFragment;
                folioPageFragment.scrollToFirst();
                folioPageFragment.scrollToAnchorId(href);
                return true;
            }
        }
        return false;
    }

    @Override
    public Config.Direction getDirection() {
        return direction;
    }

    @Override
    public void onDirectionChange(Config.Direction newDirection) {
        if (currentFragment == null) {
            return;
        }
        FolioPageFragment folioPageFragment = currentFragment;
        entryReadLocator = folioPageFragment.getLastReadLocator();
        SearchLocator searchLocatorVisible = folioPageFragment.getSearchLocatorVisible();
        direction = newDirection;
        mFolioPageViewPage.setDirection(newDirection);
        folioPageFragmentAdapte = new FolioPageFragmentAdapter(getSupportFragmentManager(), spine, bookFileName, mBookId);
        mFolioPageViewPage.setAdapter(folioPageFragmentAdapte);
        mFolioPageViewPage.setCurrentItem(currentChpterIndex);

        if (currentFragment == null) {
            return;
        }
        folioPageFragment.highlightSearchLocator(searchLocatorVisible);

    }

    @Override
    public void storeLastReadLocator(ReadLocator lastReadLocator) {
        this.lastReadLocator = lastReadLocator;
    }

    @Override
    public void toggleSystemUI() {

        if (distractionFreeMode) {
            showSystemUI();
        } else {
            hideSystemUI();
        }
    }

    @Override
    public void setDayMode() {
        actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, R.color.white)));
        toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.black));
    }

    @Override
    public void setNightMode() {
        actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, R.color.black)));
        toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.night_title_text_color));
    }

    @Override
    public int getTopDistraction(DisplayUnit unit) {
        int topDistraction = 0;
        if (!distractionFreeMode) {
            topDistraction = statusBarHeight;
            if (actionBar != null) {
                topDistraction += actionBar.getHeight();
            }
        }
        if (unit == DisplayUnit.PX) {
            return topDistraction;
        } else if (unit == DisplayUnit.DP) {
            topDistraction /= density;
            return topDistraction;

        } else {
            return 0;
        }

    }

    @Override
    public int getBottomDistraction(DisplayUnit unit) {
        int bottomDistraction = 0;
        if (!distractionFreeMode) {
            bottomDistraction = appBarLayoutNew.getNavigationBarHeight();
        }
        if (unit == DisplayUnit.PX) {
            return bottomDistraction;
        } else if (unit == DisplayUnit.DP) {
            bottomDistraction /= density;
            return bottomDistraction;

        } else {
            return 0;
        }
    }

    @Override
    public Rect getViewportRect(DisplayUnit unit) {
        Rect viewportRect = computeViewportRect();
        if (unit == DisplayUnit.PX) {
            return viewportRect;
        } else if (unit == DisplayUnit.DP) {
            viewportRect.left /= density;
            viewportRect.top /= density;
            viewportRect.right /= density;
            viewportRect.bottom /= density;
            return viewportRect;
        } else if (unit == DisplayUnit.CSS_PX) {
            viewportRect.left = (int) Math.ceil((viewportRect.left / density));
            viewportRect.top = (int) Math.ceil((viewportRect.top / density));
            viewportRect.right = (int) Math.ceil((viewportRect.right / density));
            viewportRect.bottom = (int) Math.ceil((viewportRect.bottom / density));
            return viewportRect;
        }
        return viewportRect;
    }

    @Override
    public WeakReference<FolioActivityNew> getActivity() {
        return new WeakReference(this);
    }

    @Override
    public String getStreamerUrl() {
        if (streamerUri == null) {
            streamerUri = Uri.parse(String.format(Constants.STREAMER_URL_TEMPLATE, Constants.LOCALHOST, portNumber, bookFileName));
        }
        return streamerUri.toString();
    }

    @Override
    public void play() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    private Rect computeViewportRect() {
        Rect rct = new Rect();
        Rect viewportRect = new Rect(appBarLayoutNew.getInsetsRect());
        if (distractionFreeMode) {
            viewportRect.left = 0;
        }
        viewportRect.top = getTopDistraction(DisplayUnit.PX);
        if (distractionFreeMode) {
            viewportRect.right = displayMetrics.widthPixels;
        } else {
            viewportRect.right = displayMetrics.widthPixels - viewportRect.right;
        }
        viewportRect.bottom = displayMetrics.heightPixels - getBottomDistraction(DisplayUnit.PX);
        return viewportRect;
    }

    private void showSystemUI() {
//        if (Build.VERSION.SDK_INT >= 21) {
//            View decorView = getWindow().getDecorView();
//            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
//        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            if (appBarLayoutNew != null) {
                appBarLayoutNew.setTopMargin(statusBarHeight);
            }
            onSystemUiVisibilityChange(View.SYSTEM_UI_FLAG_VISIBLE);
//        }

    }

    private void hideSystemUI() {
//        if (Build.VERSION.SDK_INT >= 21) {
//            View decorView = getWindow().getDecorView();
//            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_IMMERSIVE
//                    // Set the content to appear under the system bars so that the
//                    // content doesn't resize when the system bars hide and show.
//                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    // Hide the nav bar and status bar
//                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
//        } else {
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
            );
            onSystemUiVisibilityChange(1);
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == SEARCH) {
            if (requestCode == Activity.RESULT_CANCELED) {
                return;
            }
            searchAdapterDataBundle = data.getBundleExtra(SearchAdapter.DATA_BUNDLE);
            searchQuery = data.getCharSequenceExtra(SearchActivity.BUNDLE_SAVE_SEARCH_QUERY);
            if (requestCode == SearchActivity.ResultCode.ITEM_SELECTED.getValue()) {
                searchLocator = data.getParcelableExtra(EXTRA_SEARCH_ITEM);
                if (mFolioPageViewPage == null) {
                    return;
                }
                currentChpterIndex = getChapterIndex(Constants.HREF, searchLocator.getHref());
                mFolioPageViewPage.setCurrentItem(currentChpterIndex);
                FolioPageFragment folioPageFragment;
                if (currentFragment == null) {
                    return;
                }
                folioPageFragment = currentFragment;
                folioPageFragment.highlightSearchLocator(searchLocator);
                searchLocator = null;

            }
        } else if (requestCode == CONTENT_HIGHLIGHT && resultCode == Activity.RESULT_OK && data.hasExtra(Constants.TYPE)) {
            String type = data.getStringExtra(Constants.TYPE);
            if (type == Constants.CHAPTER_SELECTED) {
                goToChapter(data.getStringExtra(Constants.SELECTED_CHAPTER_POSITION));
            } else if (type == Constants.HIGHLIGHT_SELECTED) {
                HighlightImpl highlightImpl = data.getParcelableExtra(HIGHLIGHT_ITEM);
                currentChpterIndex = highlightImpl.getPageNumber();
                mFolioPageViewPage.setCurrentItem(currentChpterIndex);
                FolioPageFragment folioPageFragment;
                if (currentFragment == null) {
                    return;
                }
                folioPageFragment = currentFragment;
                folioPageFragment.scrollToHighlightId(highlightImpl.getRangy());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (outState != null) {
            outState.putSerializable(BUNDLE_READ_LOCATOR_CONFIG_CHANGE, lastReadLocator);
        }
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadcastManager.unregisterReceiver(searchReceiver);
        localBroadcastManager.unregisterReceiver(closeBroadcastReceiver);
        if (r2StreamerServer != null) {
            r2StreamerServer.stop();
        }
        if (isFinishing()) {
            localBroadcastManager.sendBroadcast(new Intent(FolioReader.ACTION_FOLIOREADER_CLOSED));
            FolioReader.get().retrofit = null;
            FolioReader.get().r2StreamerApi = null;

        }
    }

    private void configFolio() {
        mFolioPageViewPage = findViewById(R.id.folioPageViewPager);
        mFolioPageViewPage.addOnPageChangeListener(new DirectionalViewpager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
//                EventBus.getDefault().post();
                currentChpterIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == DirectionalViewpager.SCROLL_STATE_IDLE) {
                    int positon= mFolioPageViewPage.getCurrentItem();

                    FolioPageFragment folioPageFragment = (FolioPageFragment) folioPageFragmentAdapte.getItem(positon-1);
                    if (folioPageFragment!=null) {
                        folioPageFragment.scrollToLast();
                        if (folioPageFragment.getMWebview()!=null) {
                            folioPageFragment.getMWebview().dismissPopupWindow();
                        }
                    }
                    folioPageFragment = (FolioPageFragment) folioPageFragmentAdapte.getItem(positon+1);
                    if (folioPageFragment!=null) {
                        folioPageFragment.scrollToFirst();
                        if (folioPageFragment.getMWebview()!=null) {
                            folioPageFragment.getMWebview().dismissPopupWindow();
                        }
                    }
                }
            }
        });
        mFolioPageViewPage.setDirection(direction);
        folioPageFragmentAdapte= new FolioPageFragmentAdapter(getSupportFragmentManager(),spine,bookFileName,mBookId);
        mFolioPageViewPage.setAdapter(folioPageFragmentAdapte);
        if (searchLocator !=null) {
            currentChpterIndex= getChapterIndex(Constants.HREF,searchLocator.getHref());
            mFolioPageViewPage.setCurrentItem(currentChpterIndex);

            FolioPageFragment folioPageFragment;
            if (currentFragment == null) {
                return;
            }
            folioPageFragment = currentFragment;
            folioPageFragment.highlightSearchLocator(searchLocator);
            searchLocator=null;
        }else{
            ReadLocator readLocator;
            if(saveInstanceState == null){
                readLocator= getIntent().getParcelableExtra(EXTRA_READ_LOCATOR);
                entryReadLocator= readLocator;
            }else{
                readLocator = saveInstanceState.getParcelable(BUNDLE_READ_LOCATOR_CONFIG_CHANGE);
                lastReadLocator = readLocator;
            }
            currentChpterIndex=  getChapterIndex(readLocator);
            mFolioPageViewPage.setCurrentItem(getCurrentChapterIndex());

        }
        LocalBroadcastManager.getInstance(this).registerReceiver(
                searchReceiver,
                new IntentFilter(ACTION_SEARCH_CLEAR)
        );
    }
    private int getChapterIndex(ReadLocator readLocator){
        if (readLocator == null) {
            return 0;
        } else if (!TextUtils.isEmpty(readLocator.getHref())) {
            return getChapterIndex(Constants.HREF, readLocator.getHref());
        }

        return 0;
    }

    private int getChapterIndex(String cssString, String value) {
        for (int i = 0; i < spine.size(); i++) {
            if (cssString ==Constants.HREF) {
                if(spine.get(i).getHref() == value){
                    return i;
                }
            }
        }
        return 0;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        this.outState= outState;

        outState.putBoolean(BUNDLE_DISTRACTION_FREE_MODE, distractionFreeMode);
        outState.putBundle(SearchAdapter.DATA_BUNDLE, searchAdapterDataBundle);
        outState.putCharSequence(SearchActivity.BUNDLE_SAVE_SEARCH_QUERY, searchQuery);
    }
    private void setConfig(Bundle savedInstanceState){
        Config config;
        Config intentConfig = getIntent().getParcelableExtra(Config.INTENT_CONFIG);
        boolean overrideConfig= getIntent().getBooleanExtra(Config.EXTRA_OVERRIDE_CONFIG, false);

        Config savedConfig = AppUtilNew.getSavedConfig(this);
        if(savedInstanceState !=null){
            config=savedConfig;
        } else if (savedConfig == null) {
            if (intentConfig == null) {
                config =new  Config();
            } else {
                config = intentConfig;
            }

        } else {
            if (intentConfig != null && overrideConfig) {
                config = intentConfig;
            } else {
                config = savedConfig;
            }
        }

        if (config == null)
            config =new  Config();

        AppUtilNew.saveConfig(this, config);
        direction = config.getDirection();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == Constants.WRITE_EXTERNAL_STORAGE_REQUEST){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setupBook();
            } else {
                Toast.makeText(this, getString(R.string.cannot_access_epub_message), Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
    private void clearSearchLocator(){
        ArrayList<Fragment> fragments =  folioPageFragmentAdapte.getFragments();
        for (int i = 0; i < fragments.size(); i++) {
            FolioPageFragment folioPageFragment= (FolioPageFragment) fragments.get(i);
            folioPageFragment.clearSearchLocator();
        }
        ArrayList<Fragment.SavedState> savedStates= folioPageFragmentAdapte.getSavedStateList();
        if(savedStates!=null){
            for (int i = 0; i < savedStates.size(); i++) {
                Fragment.SavedState savedState = savedStates.get(i);
                Bundle bundle = FolioPageFragmentAdapter.getBundleFromSavedState(savedState);
                bundle.putParcelable(FolioPageFragment.BUNDLE_SEARCH_LOCATOR,null);
            }
        }


    }
}
